//
//  SmallDecisionsXjdChooseTemplateViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/7/26.
//

#import "SmallDecisionsXjdChooseTemplateViewController.h"
#import "SmallDecisionsXjdTemplateItemCell.h"
#import "SmallDecisionsXjdModel.h"
#import "SmallDecisionsXjdEditTemplateViewController.h"

@interface SmallDecisionsXjdChooseTemplateViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *templateTableView;
@property (nonatomic, strong) NSMutableArray *templateModelList;

@end

@implementation SmallDecisionsXjdChooseTemplateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择模版";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self loadXjdChooseTemplateData];
    [self templateTableView];
}

- (void)loadXjdChooseTemplateData {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *templateXjdPath = [documentPath stringByAppendingPathComponent:@"templateXjd.plist"];
    if (![fileManager fileExistsAtPath:templateXjdPath]) {
        NSString *templateXjdPath = [[NSBundle mainBundle] pathForResource:@"templateXjd" ofType:@"json"];
        NSData *templateXjdData   = [NSData dataWithContentsOfFile:templateXjdPath];
        NSArray *templateXjdList = [NSJSONSerialization JSONObjectWithData:templateXjdData options:NSJSONReadingMutableContainers error:nil];

        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSData *templatePlistData = [templateXjdList plistData];
            [self.templateModelList addObjectsFromArray:[NSArray yy_modelArrayWithClass:[SmallDecisionsXjdModel class] json:templateXjdList]];
            [templatePlistData writeToFile:templateXjdPath atomically:YES];
        });
        return;
    }

    NSArray *templateXjdList = [NSArray arrayWithContentsOfFile:templateXjdPath];
    [self.templateModelList addObjectsFromArray:[NSArray yy_modelArrayWithClass:[SmallDecisionsXjdModel class] json:templateXjdList]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.templateModelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SmallDecisionsXjdTemplateItemCell *templateItemCell = [tableView dequeueReusableCellWithIdentifier:@"SmallDecisionsXjdTemplateItemCellId" forIndexPath:indexPath];
    SmallDecisionsXjdModel *templateModel = self.templateModelList[indexPath.row];
    templateItemCell.templateTitleLabel.text = templateModel.templateTitle;
    templateItemCell.templateIconLabel.text = templateModel.templateIcon;
    @weakify(self);
    templateItemCell.templateEditFinishAction = ^(SmallDecisionsXjdTemplateItemCell * cell) {
        SmallDecisionsXjdEditTemplateViewController *xjdEditTemplateVC = [[SmallDecisionsXjdEditTemplateViewController alloc] init];
        xjdEditTemplateVC.editModel = templateModel;
        xjdEditTemplateVC.callback = ^(SmallDecisionsXjdModel * _Nonnull templateModel) {
            weak_self.templateModelList[indexPath.row] = templateModel;
            [tableView reloadData];
            [weak_self saveTemplateModelListToLocal];
        };
        [SmallDecisionsNavigatorManager pushViewController:xjdEditTemplateVC];
    };
    return templateItemCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    for (SmallDecisionsXjdModel *model in self.templateModelList) {
        model.isTemplateSelected = NO;
    }

    SmallDecisionsXjdModel *templateModel = self.templateModelList[indexPath.row];
    templateModel.isTemplateSelected = YES;
    if (self.callback) {
        self.callback(templateModel);
    }
    [self saveTemplateModelListToLocal];

    [SmallDecisionsNavigatorManager popViewControllerAnimated:YES];
}

- (void)saveTemplateModelListToLocal {
    @weakify(self);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *templateXjdPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        templateXjdPath = [templateXjdPath stringByAppendingPathComponent:@"templateXjd.plist"];

        NSArray *templateXjdList = [weak_self.templateModelList yy_modelToJSONObject];
        NSData  *templateXjdData = [templateXjdList plistData];
        [templateXjdData writeToFile:templateXjdPath atomically:YES];
    });
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return  [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return  0.0001f;
}

- (UITableView *)templateTableView {
    if (!_templateTableView) {
        _templateTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _templateTableView.delegate   = self;
        _templateTableView.dataSource = self;
        _templateTableView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_templateTableView];
        _templateTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_templateTableView registerClass:[SmallDecisionsXjdTemplateItemCell class] forCellReuseIdentifier:@"SmallDecisionsXjdTemplateItemCellId"];
        [_templateTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.top.mas_equalTo(0);
        }];
    }
    return _templateTableView;
}


- (NSMutableArray *)templateModelList {
    if(!_templateModelList) {
        _templateModelList = [[NSMutableArray alloc] init];
    }
    return _templateModelList;
}

- (UIView *)setRightBarButton {
    UIButton *rightAddTemplateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightAddTemplateBtn setTitle:@"新增模版" forState:UIControlStateNormal];
    rightAddTemplateBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
    [rightAddTemplateBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
    rightAddTemplateBtn.frame = CGRectMake(0, 0, 30, 30);
    return rightAddTemplateBtn;
}

- (void)rightBarButtonAction:(UIButton *)view {
    @weakify(self);
    SmallDecisionsXjdEditTemplateViewController *xjdEditTemplateVC = [[SmallDecisionsXjdEditTemplateViewController alloc] init];
    xjdEditTemplateVC.callback = ^(SmallDecisionsXjdModel * _Nonnull model) {
        [weak_self.templateModelList insertObject:model atIndex:0];
        [weak_self.templateTableView reloadData];
        [weak_self saveTemplateModelListToLocal];
    };

    [SmallDecisionsNavigatorManager pushViewController:xjdEditTemplateVC];
}

@end
